//获取需要从数据库渲染的所有元素
let smtit = document.querySelector(".story .nav span:last-child");
let bgtit = document.querySelector(".story .content .title h1");
let storyHot = document.querySelector(".story .content .title span");
let storyText = document.querySelector(".story .content .text p");
let storyImg = document.querySelector(".story .content .pic ul");
//'http://127.0.0.1:9000/html/test.html?s_id=8' 首页跳转过来的链接 首页自己拼接的
//'http://127.0.0.1:9000/html/story.html?s_id=8' 故事页或者分页跳转过来的链接 
let orgURL = window.location.href;
function getURL(url) {
  //截取地址中s_id=xxx 
  let str = url.match(/s_id=\d+/)[0];
  //获取s_id中xx的值
  let num = str.split("=")[1];
  return num
};
let s_id = getURL(orgURL);
let url = `/admin/storylist/${s_id}`
//promise封装ajax请求
let getData = function (url) {
  return new Promise(
    function (resolve, reject) {
      let xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status >= 200 && xhr.status < 300) {
            let result = JSON.parse(xhr.responseText);
            // console.log(result);
            resolve(result);
          } else {
            reject(new Error("Request was unsuccessful: ") + xhr.status);
          }
        }
      }
      xhr.open("GET", url, true);
      xhr.send();
    }
  );
};
//url地址传入接口拿到数据
getData(url).then((result) => {
  //console.log(result);
  //如果传入错误数据跳转到自定义404页面
  if (result.code === 201){
    window.location.href = "./404.html"
  }else{
  smtit.innerText += result.data[0].s_tit;
  bgtit.innerText = result.data[0].s_tit;
  storyHot.innerText += result.data[0].s_heat;
  storyText.innerText = result.data[0].s_text;
  let imgarr = result.data[0].s_imgs.split(",");
  let str = "";
  for (let i=0;i<imgarr.length;i++){
    str +=`<li><img src="../img/${imgarr[i]}"></li>`
  }
  storyImg.innerHTML = str;
  }
});